//
//  LOShopCarViewController.m
//  renmingongshe
//
//  Created by Mao on 2017/11/1.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "LOShopCarViewController.h"
#import "ShoppingCarListCell.h"
#import "LOCarDetailViewController.h"
#import "HeaderView.h"
#import "FooterView.h"

@interface LOShopCarViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_sections;//数据源
    NSMutableArray *_boolArr;//section勾选状态
    NSMutableArray *_editArr;//section编辑状态
    NSMutableArray *_selectedArr;//选中商品
    NSMutableArray *_cellboolArr;//cell勾选状态
    
    NSInteger _goodNum;
    NSInteger _goodPrice;
    
    NSInteger _allNum;
    NSInteger _allPrice;
}
@property (weak, nonatomic) IBOutlet UIButton *chooseAll;
@property (strong, nonatomic) UITableView *table;
@property (weak, nonatomic) IBOutlet UILabel *goodsNum;
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;

@end

@implementation LOShopCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"购物车";
    
    self.view.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    _sections = [NSMutableArray array];
    _boolArr = [NSMutableArray array];
    _selectedArr = [NSMutableArray array];
    _editArr = [NSMutableArray array];
    _cellboolArr = [NSMutableArray array];
    [self initTable];
    [self getData];
}

- (UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, WIDTH, HEIGHT-70-50) style:UITableViewStyleGrouped];
        _table.delegate = self;
        _table.dataSource = self;
        
        [self.view addSubview:_table];
    }
    return _table;
}
- (void)initTable
{
    [self.table registerClass:[FooterView class] forHeaderFooterViewReuseIdentifier:@"FooterView"];
    [self.table registerClass:[HeaderView class] forHeaderFooterViewReuseIdentifier:@"HeaderView"];
    [self.table registerNib:[UINib nibWithNibName:@"ShoppingCarListCell" bundle:nil] forCellReuseIdentifier:@"ShoppingCarListCell"];
}
- (void)getData
{
    [_sections removeAllObjects];
    [_boolArr removeAllObjects];
    [_selectedArr removeAllObjects];
    [_editArr removeAllObjects];
    [_cellboolArr removeAllObjects];
    NSDictionary *dic = @{@"userToken":[Utils getUserToken],@"type":@"0",@"page_type":@"1",@"isSettlement":@"0"};
    
    [THWManager PostHttp:API(LOShoppingCarList) Parameters:dic Success:^(id responseObject) {
        
        NSDictionary *data = responseObject[@"data"];
        
        if ([String(responseObject[@"status_code"]) isEqualToString:@"1000"]) {
            
        }else{
            [self.view Message:responseObject[@"msg"]];
            return;
        }
        
        _allNum = [data[@"goodsTotalNum"]integerValue];
        _allPrice = [data[@"goodsTotalMoney"]integerValue];
        _goodNum = _allNum;
        _goodPrice =_allPrice;
        _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_allNum];
        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_allPrice];
        
        NSDictionary *carts= data[@"carts"];
        if (carts.count > 0) {
            _sections.array = [carts allValues];
            for (int i=0; i<_sections.count; i++) {
                
                [_editArr addObject:@"0"];
                NSArray *arr = _sections[i][@"list"];
                
                NSMutableArray *ma = [NSMutableArray array];
                for (NSDictionary *d in arr) {
                    if ([d[@"isCheck"]integerValue]) {
                        [ma addObject:@"1"];
                        [_selectedArr addObject:d];
                    }else{
                        [ma addObject:@"0"];
                    }
                }
                if ([ma containsObject:@"0"]) {
                    [_boolArr addObject:@"0"];
                }else{
                    [_boolArr addObject:@"1"];
                }
                if ([_boolArr containsObject:@"0"]) {
                    _chooseAll.selected = NO;
                }else{
                    _chooseAll.selected = YES;
                }
                [_cellboolArr addObject:ma];
            }
        }
        
        [self.table reloadData];
        
    } andFalse:^(NSError *error) {
        
    }];
}
- (IBAction)chooseAll:(UIButton*)sender {
    sender.selected = !sender.selected;
    
    NSMutableArray *muArr = [NSMutableArray array];
    NSInteger addNum = 0;
    NSInteger addPrice = 0;
    for (int i=0; i<_sections.count; i++) {
        
        NSArray *arr = _sections[i][@"list"];
        for (NSDictionary *d in arr) {
            [muArr addObject:d];
            
            
            addNum += [d[@"cartNum"]integerValue];
            
            addPrice += [d[@"cartNum"]integerValue]*[d[@"shopPrice"]integerValue];
            
        }
    }
    if (sender.selected) {
        
        _goodNum = addNum;
        _goodPrice =addPrice;
        [_selectedArr addObjectsFromArray:muArr];
    }else{
        _goodNum = 0;
        _goodPrice =0;
        [_selectedArr removeAllObjects];
    }
    _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_goodNum];
    _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_goodPrice];
    
    for (int i=0; i<_boolArr.count; i++) {
        [_boolArr replaceObjectAtIndex:i withObject:@(sender.selected)];
        
        NSMutableArray *ma = [[NSMutableArray alloc]initWithArray:_cellboolArr[i]];
        for (int i=0; i<ma.count; i++) {
            [ma replaceObjectAtIndex:i withObject:@(sender.selected)];
        }
        [_cellboolArr replaceObjectAtIndex:i withObject:ma];
    }
    
    [self.table reloadData];
    [self choosePush:muArr choosed:sender.selected suc:^{
        
    } fail:^{
        
    }];
}
- (IBAction)payClick:(id)sender {
    if (!_selectedArr.count) {
        [self.view Message:@"未选择商品"];
        return;
    }
    NSArray *list = _selectedArr;
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *dic in list) {
        NSDictionary *d = @{@"cartId":dic[@"cartId"],@"isCheck":@"1",@"cartNum":dic[@"cartNum"]};
        [arr addObject:d];
    }
    NSData *data=[NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *para = @{@"type":@"0",@"userToken":[Utils getUserToken],@"carts_info":jsonStr};
    
    [THWManager PostHttp:API(LOSetShoppingCar) Parameters:para Success:^(id responseObject) {
        
        LOCarDetailViewController *detail = [[LOCarDetailViewController alloc] init];
        detail.sucSubmit = ^{
            [self getData];
        };
        [self.navigationController pushViewController:detail animated:YES];
    } andFalse:^(NSError *error) {
        
    }];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _sections[section][@"list"];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *d = _sections[indexPath.section][@"list"][indexPath.row];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:d];
    ShoppingCarListCell *cell = [_table dequeueReusableCellWithIdentifier:@"ShoppingCarListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.choosed = [_cellboolArr[indexPath.section][indexPath.row]boolValue];
    cell.edited = [_editArr[indexPath.section]boolValue];
    
    __weak ShoppingCarListCell *weakCell = cell;
    cell.click = ^(BOOL choosed){
        
       weakCell.choosed = choosed;
        
        NSMutableArray *ma = [[NSMutableArray alloc]initWithArray:_cellboolArr[indexPath.section]];
        [ma replaceObjectAtIndex:indexPath.row withObject:@(choosed)];
        [_cellboolArr replaceObjectAtIndex:indexPath.section withObject:ma];
        
        if (choosed) {
            BOOL have=NO;
            for (int i=0; i<ma.count; i++) {
                if (![ma[i]boolValue]) {
                    have = YES;
                    break;
                }
            }
            if (!have) {
                [_boolArr replaceObjectAtIndex:indexPath.section withObject:@(choosed)];
                
                [self.table reloadData];
                
            }
        }else{
            [_boolArr replaceObjectAtIndex:indexPath.section withObject:@(choosed)];
            [self.table reloadData];
            
            
        }
        [self choosePush:@[dic] choosed:choosed suc:^{
            
        } fail:^{
            
        }] ;
        
        NSInteger addNum;
        if (choosed) {
            [_selectedArr addObject:dic];
            addNum = [dic[@"cartNum"]integerValue];
        }else{
            [_selectedArr removeObject:dic];
            addNum = -[dic[@"cartNum"]integerValue];
        }
        NSInteger addPrice = addNum*[dic[@"shopPrice"]integerValue];
        _goodPrice = _goodPrice+addPrice;
        _goodNum = _goodNum+addNum;
        
        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_goodPrice];
        _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_goodNum];
    };
    cell.addOrsubGoods = ^(NSString *num){
        
        
        
        if (weakCell.choosed) {
            NSInteger addNum = (num.integerValue - [dic[@"cartNum"]integerValue]);
            NSInteger addPrice = addNum*[dic[@"shopPrice"]integerValue];
            _goodPrice = _goodPrice+addPrice;
            _goodNum = _goodNum+addNum;
            
            _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_goodPrice];
            _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_goodNum];
            
            NSArray *tmpa = [NSArray arrayWithArray:_selectedArr];
            for (NSDictionary *d in tmpa) {
                if ([d[@"cartId"]isEqual:dic[@"cartId"]]) {
                    [_selectedArr removeObject:d];
                    [_selectedArr addObject:dic];
                }
            }
        }
        NSMutableDictionary *di = [[NSMutableDictionary alloc]initWithDictionary:_sections[indexPath.section]];
        NSMutableArray *a = [NSMutableArray array];
        a.array = _sections[indexPath.section][@"list"];
        
        [dic setObject:num forKey:@"cartNum"];
        
        [a replaceObjectAtIndex:indexPath.row withObject:dic];
        [di setObject:a forKey:@"list"];
        [_sections replaceObjectAtIndex:indexPath.section withObject:di];
        
        //[self.table reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    };
    cell.delGoods = ^{
        [self delGoods:dic[@"cartId"] atIndexPath:indexPath];
    };
    [cell cellConfigwithDic:dic];
    
    return cell;
}
- (void)delGoods:(NSString *)cartId atIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *para = @{@"userToken":[Utils getUserToken],@"type":@"0",@"cartId":cartId};
    [THWManager PostHttp:API(LODelShoppingCar) Parameters:para Success:^(id responseObject) {
        
        if ([responseObject[@"status_code"]integerValue]==1000) {
            
            NSMutableDictionary *di = [[NSMutableDictionary alloc]initWithDictionary:_sections[indexPath.section]];
            NSMutableArray *a = [NSMutableArray array];
            a.array = _sections[indexPath.section][@"list"];
            
            [a removeObjectAtIndex:indexPath.row];
            
            [di setObject:a forKey:@"list"];
            if (a.count==0) {
                
                NSArray *a = [NSArray arrayWithArray:_sections];
                for (NSDictionary *d in a) {
                    if ([d[@"shopId"]integerValue] ==[di[@"shopId"]integerValue]) {
                        [_sections removeObject:d];
                    }
                }
                [_cellboolArr removeObjectAtIndex:indexPath.section];
                [_boolArr removeObjectAtIndex:indexPath.section];
                [_editArr removeObjectAtIndex:indexPath.section];
                
            }else{
                [_sections replaceObjectAtIndex:indexPath.section withObject:di];
            }
            
            [self.table reloadData];
        }
        
    } andFalse:^(NSError *error) {
        
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HeaderView"];
    //[header removeAllSubviews];
    header.chooseClick = ^(UIButton *btn) {
        [self chooseClick:btn];
    };
    header.editClick = ^(UIButton *btn) {
        [self editClick:btn];
    };
    NSDictionary *data = _sections[section];

    header.btn.selected = [_boolArr[section]boolValue];
    header.btn.tag = section;
    
    header.shopName.text = data[@"shopName"];
    
    header.btn1.tag = section;
    header.btn1.selected = [_editArr[section]boolValue];
    
    return header;
}
- (void)choosePush:(NSArray *)list choosed:(BOOL)isCheck suc:(void(^)(void))suc fail:(void(^)(void))fai
{
//    btn.selected = !btn.selected;
//    NSArray *list = _sections[btn.tag][@"list"];
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in list) {
            NSDictionary *d = @{@"goodsId":dic[@"goodsId"],@"isCheck":isCheck? @"1":@"0",@"goodsSpecId":dic[@"goodsSpecId"]};
            [arr addObject:d];
        }
        NSData *data=[NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *para = @{@"type":@"0",@"userToken":[Utils getUserToken],@"carts_info":jsonStr};
        
        [THWManager PostHttp:API(LOSetHookBtn) Parameters:para Success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            
            
            suc();
            
            
        } andFalse:^(NSError *error) {
            NSLog(@"%@",error);
            fai();
            
        }];
    
}
- (void)editClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    NSArray *list = _sections[btn.tag][@"list"];
    
    if (!btn.selected) {
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in list) {
            NSDictionary *d = @{@"cartId":dic[@"cartId"],@"isCheck":@"1",@"cartNum":dic[@"cartNum"]};
            [arr addObject:d];
        }
        NSData *data=[NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *para = @{@"type":@"0",@"userToken":[Utils getUserToken],@"goodsInfo":jsonStr};
        
        [THWManager PostHttp:API(LOEditShoppingCar) Parameters:para Success:^(id responseObject) {

            NSLog(@"%@",responseObject);
            [_editArr replaceObjectAtIndex:btn.tag withObject:@(btn.selected)];
            //[_boolArr replaceObjectAtIndex:btn.tag withObject:@"0"];
//            NSMutableArray *ma = [[NSMutableArray alloc]initWithArray:_cellboolArr[btn.tag]];
//            for (int i=0; i<ma.count; i++) {
//                [ma replaceObjectAtIndex:i withObject:@(btn.selected)];
//            }
//            [_cellboolArr replaceObjectAtIndex:btn.tag withObject:ma];
            
            [self.table reloadData];
            
            //self.chooseAll.enabled = YES;
        } andFalse:^(NSError *error) {
            
            btn.selected = !btn.selected;
            NSLog(@"%@",error);
        }];
    }else{
        //self.chooseAll.enabled = NO;
        
        [_editArr replaceObjectAtIndex:btn.tag withObject:@(btn.selected)];
//        [_boolArr replaceObjectAtIndex:btn.tag withObject:@"0"];
//
//        NSMutableArray *ma = [[NSMutableArray alloc]initWithArray:_cellboolArr[btn.tag]];
//        for (int i=0; i<ma.count; i++) {
//            [ma replaceObjectAtIndex:i withObject:@"0"];
//        }
//        [_cellboolArr replaceObjectAtIndex:btn.tag withObject:ma];
        
        [self.table reloadData];
        
//        NSMutableArray *arr=[NSMutableArray array];
//        for (NSDictionary *d in list) {
//            if ([_selectedArr containsObject:d]) {
//                [_selectedArr removeObject:d];
//                [arr addObject:d];
//            }
//        }
//
//        NSInteger addNum = 0;
//        NSInteger addPrice = 0;
//        for (NSDictionary *dic in arr) {
//            addNum -= [dic[@"cartNum"]integerValue];
//            addPrice -= [dic[@"cartNum"]integerValue]*[dic[@"shopPrice"]integerValue];
//        }
//        _goodPrice = _goodPrice+addPrice;
//        _goodNum = _goodNum+addNum;
//
//        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_goodPrice];
//        _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_goodNum];
    }
}

- (void)chooseClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    [_boolArr replaceObjectAtIndex:btn.tag withObject:@(btn.selected)];
    
    
    NSMutableArray *ma = [[NSMutableArray alloc]initWithArray:_cellboolArr[btn.tag]];
    for (int i=0; i<ma.count; i++) {
        [ma replaceObjectAtIndex:i withObject:@(btn.selected)];
    }
    [_cellboolArr replaceObjectAtIndex:btn.tag withObject:ma];
    
    [self.table reloadData];
    
     //   [_table reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationFade];
    
    NSArray *arr = _sections[btn.tag][@"list"];
    NSMutableArray *tmpArr = [[NSMutableArray alloc]initWithArray:arr];
    
    NSInteger addNum = 0;
    NSInteger addPrice = 0;
    
    
    if (btn.selected) {
        for (NSDictionary *dic in _selectedArr) {
            if ([tmpArr containsObject:dic]) {
                [tmpArr removeObject:dic];
            }
        }
        
        [_selectedArr addObjectsFromArray:tmpArr];
        for (NSDictionary *dic in tmpArr) {
            addNum += [dic[@"cartNum"]integerValue];
            addPrice += [dic[@"cartNum"]integerValue]*[dic[@"shopPrice"]integerValue];
        }
    }else{
        
        NSMutableArray *a = [NSMutableArray array];
        for (NSDictionary *dic in tmpArr) {
            if ([_selectedArr containsObject:dic]) {
                [_selectedArr removeObject:dic];
                [a addObject:dic];
            }
        }
        
//        [_selectedArr removeObjectsInArray:tmpArr];
        for (NSDictionary *dic in a) {
            addNum -= [dic[@"cartNum"]integerValue];
            addPrice -= [dic[@"cartNum"]integerValue]*[dic[@"shopPrice"]integerValue];
        }
    }
    _goodPrice = _goodPrice+addPrice;
    _goodNum = _goodNum+addNum;
    
    _totalPrice.text = [NSString stringWithFormat:@"总计：%ld元",_goodPrice];
    _goodsNum.text = [NSString stringWithFormat:@"产品数量：%ld",_goodNum];
    
    [self choosePush:arr choosed:btn.selected suc:^{
        
    } fail:^{
        
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    FooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"FooterView"];
//    footer.backgroundColor =[UIColor colorWithHex:0xf2f2f2];
//    return footer;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView == self.table){
//        UITableView *tableview = (UITableView *)scrollView;
//        CGFloat sectionHeaderHeight = 70;
//        CGFloat sectionFooterHeight = 60;
//        CGFloat offsetY = tableview.contentOffset.y;
//        if (offsetY >= 0 && offsetY <= sectionHeaderHeight){
//            tableview.contentInset = UIEdgeInsetsMake(-offsetY, 0, -sectionFooterHeight, 0);
//        }else if (offsetY >= sectionHeaderHeight && offsetY <= tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight){
//            tableview.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, -sectionFooterHeight, 0);
//        }else if (offsetY >= tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight && offsetY <= tableview.contentSize.height - tableview.frame.size.height){
//            tableview.contentInset = UIEdgeInsetsMake(-offsetY, 0, -(tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight), 0);
//        }
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
